package display2012;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;

import interfaces.IDisplay;

public class DisplayUDPClient extends Thread implements IDisplay{

	DatagramSocket clientSocket;
	IDisplay display;
	boolean stop;
	
	public DisplayUDPClient(IDisplay display, String IP, int port) throws UnknownHostException, SocketException{
		this.display = display;
		this.clientSocket = new DatagramSocket(4445);
	}
	
	@Override
	public void update(String v) {
		display.update(v);		
	}

	@Override
	public String getCurVarToShow() {
		return display.getCurVarToShow();
	}
	
	public void stopRunning(){
		stop = true;
	}
	
	@Override
	public void run(){
		try {
			register();
			readAck();
			while(!stop){
				int value = receive();
				update("" + value);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
		
	private void register() throws IOException{
		send(-1);		
	}
	
	private void readAck() throws IOException {
		int value = receive();
		if( value == -2)
			return;
		else
			System.out.println("Error reading ack");
	}
	
	private void send(int value) throws IOException
	{
		byte[] buf = ByteBuffer.allocate(4).putInt(value).array();
		DatagramPacket packet = new DatagramPacket(buf, buf.length);
		clientSocket.send(packet);
	}
	
	private int receive() throws IOException
	{
		byte[] buf = new byte[4];
		DatagramPacket packet = new DatagramPacket(buf, buf.length);
		clientSocket.receive(packet);
		int value = ByteBuffer.allocate(4).put(packet.getData()).getInt();
		return value;
	}

}
